package view;

import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.rmi.RemoteException;
import java.util.Date;

import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;
import javax.swing.ListCellRenderer;

import rmi.Discussion;
import rmi.DiscussionInterface;
import rmi.Me;
import rmi.UserBuffer;
import controler.xmlReadWrite;

/**
 * @author REMY Timothée and CARTIER Arthur
 *
 */
public class Clist extends JList implements ListCellRenderer, MouseListener {
	public class OnClose implements ActionListener {
		private final Component onglet;
		private final Discussion discussion;

		public OnClose(final Component onglet, final Discussion discussion) {
			super();
			this.onglet = onglet;
			this.discussion = discussion;
		}

		@Override
		public void actionPerformed(final ActionEvent ae) {
			for (final DiscussionInterface d : discussion.getListDiscussions()) {
				try {
					d.leave(me.getPseudo());
				} catch (final RemoteException e) {
					// try once again
					try {
						d.leave(me.getPseudo());
					} catch (final RemoteException e1) {
						// Too bad
					}
				}
			}
			discussion.getListDiscussions().clear();
			if (me.getSaveDiscussionsFolder() == null
					|| me.getSaveDiscussionsFolder().isEmpty()) {
				int result = 0;
				final JFileChooser jfc = new JFileChooser("~");
				jfc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
				jfc.setDialogTitle("Select the backup folder for your discussion");
				result = jfc.showSaveDialog(mainWindow);

				if (result == JFileChooser.APPROVE_OPTION) {
					try {
						me.setSaveDiscussionsFolder(jfc.getSelectedFile()
								.getCanonicalPath().toString());

					} catch (final FileNotFoundException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (final IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			}

			try {
				xmlReadWrite.saveOneDiscussion(discussion,
						me.getSaveDiscussionsFolder());
			} catch (final FileNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			discussTabbedPane.remove(onglet);

		}

	}

	/**
	 * 
	 */
	private static final long serialVersionUID = 3921718705561165775L;
	private DefaultListModel modelList;
	private JTabbedPane discussTabbedPane;
	private MainWindow mainWindow;
	private Me me;

	private Date AddSb;

	/**
	 * 
	 */
	public Clist() {
		super();
	}

	public Clist(final DefaultListModel modelList) {
		super();
		this.modelList = modelList;
	}

	/**
	 * @param modelList
	 */
	public Clist(final DefaultListModel modelList,
			final JTabbedPane allDiscuss, final Me me, final MainWindow mw) {
		super();
		discussTabbedPane = allDiscuss;
		this.me = me;
		mainWindow = mw;
		this.modelList = modelList;
		setModel(this.modelList);
		setLayoutOrientation(JList.VERTICAL);
		setVisibleRowCount(25);
		setVisible(true);
		addMouseListener(this);
	}

	public void addOneDiscussion(final String name, final OneDiscussionTab one) {
		Component temp;
		temp = discussTabbedPane.add(name, one);

		final JPanel p1 = new JPanel();
		p1.setOpaque(false);
		final JLabel title = new JLabel(name);

		final JButton btnX = new JButton();
		btnX.setPreferredSize(new Dimension(10, 10));

		btnX.setBackground(new Color(255, 0, 0));
		btnX.addActionListener(new OnClose(temp, one.getDiscussion()));
		System.out.println(temp.getClass());

		p1.add(title);
		p1.add(btnX);
		discussTabbedPane.setTabComponentAt(
				discussTabbedPane.getTabCount() - 1, p1);
	}

	@Override
	public Component getListCellRendererComponent(final JList l,
			final Object value, final int index, final boolean isSelected,
			final boolean cellHasFocus) {
		final Color selectedColor = Color.blue;
		final String s = value.toString();
		if (isSelected) {
			setBackground(l.getSelectionBackground());
			setForeground(selectedColor);
			setToolTipText(s + "  " + index);
			// setIcon(selectIcon);
		} else {
			setBackground(l.getBackground());
			setForeground(l.getForeground());
			setToolTipText(s);
			// setIcon(icon);
		}
		setEnabled(l.isEnabled());
		setFont(l.getFont());
		setOpaque(true);

		return this;
	}

	/**
	 * @return
	 */
	public DefaultListModel getModelList() {
		return modelList;
	}

	@Override
	public void mouseClicked(final MouseEvent e) {
		if (e.getClickCount() == 2) {
			if (getModel().getSize() > 0) {
				final int index = locationToIndex(e.getPoint());
				final Object item = modelList.getElementAt(index);
				UserBuffer distantUser = null;
				if (item instanceof UserBuffer) {
					distantUser = (UserBuffer) item;

				}
				if (distantUser.isConnected()) {
					ensureIndexIsVisible(index);
					System.out.println("Double clicked on " + item);

					Discussion disc;
					try {
						disc = new Discussion(me);
						System.out.println("main window NonNull?"
								+ (mainWindow != null));
						mainWindow.getDiscussionThatAreAlreadyDisplayed().add(
								disc);
						final OneDiscussionTab one = new OneDiscussionTab(disc,
								me);
						final String name = item.toString();

						addOneDiscussion(name, one);
						distantUser.initDiscussion(disc);

					} catch (final Exception e1) {

						e1.printStackTrace();
					}
				}

			}
			discussTabbedPane.repaint();

		}
	}

	@Override
	public void mouseEntered(final MouseEvent arg0) {

	}

	@Override
	public void mouseExited(final MouseEvent arg0) {
	}

	@Override
	public void mousePressed(final MouseEvent arg0) {
		AddSb = new Date();
	}

	@Override
	public void mouseReleased(final MouseEvent e) {
		final Date temp = new Date();
		if (temp.getTime() - AddSb.getTime() > 1500) {
			final OneDiscussionTab odt = (OneDiscussionTab) discussTabbedPane
					.getSelectedComponent();
			final int index = locationToIndex(e.getPoint());
			final Object item = modelList.getElementAt(index);
			if (item instanceof UserBuffer) {
				final UserBuffer distantUser = (UserBuffer) item;
				try {
					distantUser.initDiscussion(odt.getDiscussion());
				} catch (final RemoteException e1) {
					// TWe try once again
					try {
						distantUser.initDiscussion(odt.getDiscussion());
					} catch (final RemoteException e2) {
						// too bad

					}
				}
			} else {
				System.out
						.println("L'item séléctionner n'est pas un userbuffer");
			}

		}
	}

	/**
	 * @param modelList
	 */
	public void setModelList(final DefaultListModel modelList) {
		this.modelList = modelList;
	}

}
